<template>
    <div style="padding-top: 20px">
        <page-main>
          <SearchForm :data-form="formInline" :useAdd="true" :searchOptions="searchOptions" @on-search="onSearch" @onReset="onSearch">
        </SearchForm>
            <div style="margin-bottom: 20px" class="btn-box">
                <el-button type="primary" @click="showAddFrom">新增</el-button>
                <el-button @click="importData">导入</el-button>
                <el-button @click="editRow">编辑</el-button>
                <el-button :disabled="selectItem.length==0" @click="deleteRow">删除</el-button>
            </div>
            <PubilcTable :table-data="tableData" :list-config="columns" :showSelect="tableData.length > 0 ? true : false" :page-data="pageData" @on-action="onAction"  @on-selectChange="changeSelectItem"/>
        </page-main>
        <eForm :dialog-visible="dialogVisible" :is-add="isAdd" :formData="formData" :columns="columns" @on-submit="formSubmit" @handle-close="handleClose"/>
        <ImportForm :dialog-visible="dialogVisible2" :downLoading='downLoading' :acceptOption='acceptOption' :show-down="true" @on-submit="formSubmit2" @downFile="downFile"  @handle-close="handleClose"/>
    </div>
</template>
<script  setup>
import { onMounted, reactive, ref, nextTick } from 'vue'
import eForm from '../components/addDataValueForm.vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import api from '@/api/index'
import { downloadFile } from '@/util/downFile'

const formInline = reactive({})
const dialogVisible = ref(false)
const dialogVisible2 = ref(false)
const downLoading = ref(false)
const acceptOption = ref('.xls,.xlsx')
const isAdd = ref('add')
const pageData = reactive({
    pageNum: 1,
    pageSize: 10,
    total: 0
})
const formData = ref({})
const options = ref({})
const selectItem = ref([])
const sourceId = ref(null)
const searchOptions = ref([])
const rules = reactive({
    name: [
        {
            required: true,
            message: 'Please input Activity name',
            trigger: 'blur'
        }
    ],
    code: [
        {
            required: true,
            message: 'Please input Activity name',
            trigger: 'blur'
        }
    ]
})

const tableData = ref([])
const columns = ref([])

onMounted(()=>{
    const data = localStorage.getItem('detailDataValue');
    if(data){
        const newData = {...JSON.parse(data)}
        sourceId.value = newData.sourceId
        nextTick(()=>{
            searchOptions.value = newData.searchOptions || []
            columns.value = newData.columnsOptions || []
        })
        onSearch()
    }
})

const onSearch = () => {
    const params = {sourceId: sourceId.value,conditions: {...formInline.value},...pageData}
    api.dataMaintenance.getConditionById(params).then((res)=>{
        tableData.value = res.list
        pageData.total = res.total
    })
}
const deleteRow = (val)=>{
    if(selectItem.value.length > 0){
        ElMessageBox.confirm('确定删除此枚举信息吗？删除后将不可恢复。', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            let ids = (selectItem.value || []).map((item) =>{
                return item._id
            });
            const params = {
                ids: ids.toString(),
                sourceId: sourceId.value
            }
            api.dataMaintenance.deleteTableValueByIds(params).then((res)=>{
                ElMessage({
                    type: 'success',
                    message: '删除成功!'
                });
                onSearch()
            })
        })
    }else{
        ElMessage({
            type: 'error',
            message: '请至少勾选一项数据!'
        });
    }
}
const changeSelectItem = (data)=>{
    selectItem.value = data
}
const editRow = () => {
    if(selectItem.value.length > 0){
        if(selectItem.value.length > 1){
            ElMessage({
                type: 'error',
                message: '最多勾选一项数据!'
            });
        }else{
            isAdd.value = 'edit'
            formData.value = selectItem.value[0]
            dialogVisible.value = true
        }
    }else{
        ElMessage({
            type: 'error',
            message: '请至少勾选一项数据!'
        });
    }
}
const onAction = ([item, row]) => {
    const obj = {
        'del': deleteRow,
        'edit': editRow,
        'pageNum': onSearch,
        'pageSize': onSearch
    }
    if (typeof item === 'string') {
        pageData[item] = row
        if (item === 'pageSize') pageData.pageNum = 1
        obj[item]()
    } else {
        obj[item.alias](row)
    }
}

const showAddFrom = () => {
    dialogVisible.value = true
    isAdd.value = 'add'
}
const formSubmit = (val)=>{
    const newData = val
    newData.id = newData._id
    const params = {sourceId: sourceId.value, values: newData}
    console.log(isAdd.value)
    if(isAdd.value === 'add'){
        api.dataMaintenance.createDataValue(params).then((res)=>{
            ElMessage({
                type: 'success',
                message: '保存成功!'
            });
            onSearch()
        })
    }else{
        api.dataMaintenance.updateDataValue(params).then((res)=>{
            ElMessage({
                type: 'success',
                message: '修改成功!'
            });
            onSearch()
        })
    }
}
const formSubmit2 = (val)=>{
    if(val && val.file){
        let fd = new FormData()
        fd.append('file', val.file)
        fd.append('sourceId', sourceId.value)
        api.dataMaintenance.importTable(fd).then((res)=>{
            ElMessage({
                type: 'success',
                message: '导入成功!'
            });
            dialogVisible2.value = false
            onSearch()
        })
    }else{
        return
    }
}
const handleClose = val => {
    dialogVisible.value = val
    dialogVisible2.value = val
}
const importData = () =>{
    dialogVisible2.value = true
}
const downFile = ()=>{
    downLoading.value = true
    api.dataMaintenance.getTempBySourceId(sourceId.value).then((res)=>{
        downloadFile(res, '添加值模板', 'xlsx')
        ElMessage({
            type: 'success',
            message: '导出成功!'
        });
        downLoading.value = false
    })
}
</script>

<style lang="scss" scoped>
</style>
